package com.ny.service.impl;

import com.ny.entity.Result;
import com.ny.entity.User;
import com.ny.mapper.UserMapper;
import com.ny.service.EmailService;
import com.ny.service.UserService;

import com.ny.until.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.GetMapping;

import javax.annotation.Resource;

@Service
public class UserServiceImpl implements UserService {
//
//    @Autowired
//    private UserMapper userMapper;

    @Resource
    private UserMapper userMapper;
    @Autowired
    private EmailService emailService;
    @Autowired
    private RedisTemplate<String, String> redisTemplate;


    // 实现用户查询逻辑（密码MD5加密后比对）
    @Override
    public User findUser(String username, String password) {
        // 先通过用户名查找用户
        User user = userMapper.findUserByName(username);
        if (user == null) {
            return null;
        }
        
        // 检查密码是否匹配（支持明文和MD5加密两种方式）
        if (user.getPassword().equals(password) || user.getPassword().equals(PasswordUtil.md5(password))) {
            return user;
        }
        
        return null;
    }
    
    @Override
    public User findUserByName(String username) {
        return userMapper.findUserByName(username);
    }

    @Override
    public int addUser(User user) {
//        // 把数据交给数据库之前先进行加密：MD5
//        String  pwd = PasswordUtil.encryptPassword(user.getPassword());// 进行加密  pwd = gfalk;hgalkhg;
//        user.setPassword(pwd);// 把加密的密码交给user
        return userMapper.addUser(user);
    }

    @Override
    public User findUserByEmail(String email)
    {

        return userMapper.findUserByEmail( email);
    }

    @Override
    public int updatePassword(String password, String email) {
        String pwd = PasswordUtil.md5(password);
        return userMapper.updatePassword(password,email);
    }
    @Override
    public void sendToEmail(String toEmail) {
        // 执行发送验证码的逻辑
        emailService.sendEmail(toEmail,emailService.getCode());
        // 把验证码存储起来Redis中。
    }
    @Override
    public boolean checkCode(String toEmail, String code) {// 输入的验证码和Redis中存储的验证码进行比较
        // 获取Redis中存储的验证码
        ValueOperations<String, String> ops = redisTemplate.opsForValue();
        String redisCode = ops.get(toEmail);
        // 判断验证码是否一致
        return redisCode.equals(code);
    }

}